/**
 * 
 */
package com.sony.csl.positioning.publictransport.model.network.io;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;

import com.sony.csl.j2me.io.FileAccess;
import com.sony.csl.j2me.util.Logger;
import com.sony.csl.positioning.publictransport.model.network.*;
import com.sony.csl.positioning.publictransport.model.network.xml.*;


/**
 * @author mstevens
 *
 */
public class LoadNetworkFromXML_J2ME
{

	public static PublicTransportNetwork parseNetworkXML(String networkName, String networkXMLFilesPath) throws Exception
	{
	
		//Lines
		Vector lines = null;
		String linesFilePath = networkXMLFilesPath + "Lines.xml";
		if(FileAccess.doesFileOrFolderExist(linesFilePath))
		{
			//Load Lines XML file:
			FileConnection fc;
			InputStream is;
			try
			{
				fc = (FileConnection) Connector.open(linesFilePath, Connector.READ);
				is = fc.openInputStream();
			}
			catch (Exception ex)
			{
				throw new Exception("Error upon opening Lines XML file (" + linesFilePath + "): " + ex.getMessage());
			}
			LinesHandler linesHandler = new LinesHandler();
			try
			{
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser saxParser = factory.newSAXParser();
				InputSource inputSource = new InputSource(is);
				saxParser.parse(inputSource, linesHandler);
			}
			catch(Exception ex)
			{
				throw new Exception("Error upon parsing Lines XML file (" + linesFilePath + "): " + ex.getMessage());
			}
			is.close();
			fc.close();
			lines = linesHandler.getLines();
		}
		else
			throw new Exception("Lines XML file (" + linesFilePath + ") does not exist");
		
		Hashtable lineID2Line = new Hashtable();
		Enumeration linesEnum = lines.elements();
		while(linesEnum.hasMoreElements())
		{
			Line line = (Line) linesEnum.nextElement();
			lineID2Line.put(new Long(line.getID()), line);
		}
		
		//Stations
		Vector stations = null;
		String stationsFilePath = networkXMLFilesPath + "Stations.xml";
		if(FileAccess.doesFileOrFolderExist(stationsFilePath))
		{
			//Load Lines XML file:
			FileConnection fc;
			InputStream is;
			try
			{
				fc = (FileConnection) Connector.open(stationsFilePath, Connector.READ);
				is = fc.openInputStream();
			}
			catch (Exception ex)
			{
				throw new Exception("Error upon opening Stations XML file (" + stationsFilePath + "): " + ex.getMessage());
			}
			StationsHandler stationsHandler = new StationsHandler();
			try
			{
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser saxParser = factory.newSAXParser();
				InputSource inputSource = new InputSource(is);
				saxParser.parse(inputSource, stationsHandler);
			}
			catch(Exception ex)
			{
				throw new Exception("Error upon parsing Stations XML file (" + stationsFilePath + "): " + ex.getMessage());
			}
			is.close();
			fc.close();
			stations = stationsHandler.getStations();
		}
		else
			throw new Exception("Stations XML file (" + stationsFilePath + ") does not exist");
		
		Hashtable stationID2Station = new Hashtable();
		Enumeration stationsEnum = stations.elements();
		while(stationsEnum.hasMoreElements())
		{
			Station station = (Station) stationsEnum.nextElement();
			stationID2Station.put(new Long(station.getID()), station);
		}
		
		//Station entrances/exits
		//Enumeration stationEnum = stations.elements();
		//while(stationEnum.hasMoreElements())
		//	((Station) stationEnum.nextElement()).addEntranceExit(null, null, null); //dummy
		//TODO: real entrances/exits
				
		//TODO: Station connections

		if(lines == null || stations == null)
			throw new Exception("Parsing of Lines or Stations failed"); //should never happen

		//Routes
		Vector routes = null;
		String routesFilePath = networkXMLFilesPath + "Routes.xml";
		if(FileAccess.doesFileOrFolderExist(routesFilePath))
		{
			//Load Lines XML file:
			FileConnection fc;
			InputStream is;
			try
			{
				fc = (FileConnection) Connector.open(routesFilePath, Connector.READ);
				is = fc.openInputStream();
			}
			catch (Exception ex)
			{
				throw new Exception("Error upon opening Routes XML file (" + routesFilePath + "): " + ex.getMessage());
			}
			RoutesHandler routesHandler = new RoutesHandler(lineID2Line, stationID2Station);
			try
			{
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser saxParser = factory.newSAXParser();
				InputSource inputSource = new InputSource(is);
				saxParser.parse(inputSource, routesHandler);
			}
			catch(Exception ex)
			{
				throw new Exception("Error upon parsing Routes XML file (" + routesFilePath + "): " + ex.getMessage());
			}
			is.close();
			fc.close();
			routes = routesHandler.getRoutes();
		}
		else
			throw new Exception("Routes XML file (" + routesFilePath + ") does not exist");
		
		if(routes == null)			
			throw new Exception("Parsing Routes failed"); //should never happen

		Hashtable routeID2Route = new Hashtable();
		Enumeration routesEnum = routes.elements();
		while(routesEnum.hasMoreElements())
		{
			Route route = (Route) routesEnum.nextElement();
			routeID2Route.put(new Long(route.getID()), route);
		}
		
		//SharedPlatforms
		Vector sharedPlatforms = null;
		String sharedPlatformsFilePath = networkXMLFilesPath + "SharedPlatforms.xml";
		if(FileAccess.doesFileOrFolderExist(sharedPlatformsFilePath))
		{
			//Load Lines XML file:
			FileConnection fc;
			InputStream is;
			try
			{
				fc = (FileConnection) Connector.open(sharedPlatformsFilePath, Connector.READ);
				is = fc.openInputStream();
				SharedPlatformsHandler sharedPlatformsHandler = new SharedPlatformsHandler(lineID2Line, stationID2Station, routeID2Route);
				try
				{
					SAXParserFactory factory = SAXParserFactory.newInstance();
					SAXParser saxParser = factory.newSAXParser();
					InputSource inputSource = new InputSource(is);
					saxParser.parse(inputSource, sharedPlatformsHandler);
				}
				catch(Exception ex)
				{
					Logger.logLine("Error upon parsing SharedPlatforms XML file (" + sharedPlatformsFilePath + "): " + ex.getMessage());
				}
				is.close();
				fc.close();
				sharedPlatforms = sharedPlatformsHandler.getSharedPlatforms();			
			}
			catch (Exception ex)
			{
				Logger.logLine("Error upon opening SharedPlatforms XML file (" + sharedPlatformsFilePath + "): " + ex.getMessage());
			}			
		}
		else
			throw new Exception("Routes XML file (" + routesFilePath + ") does not exist");
		
		return new PublicTransportNetwork(networkName, lineID2Line, stationID2Station, routeID2Route, sharedPlatforms);
	}
	
}
